package com.qf.dao.impl;

import com.qf.dao.GoodsDao;
import com.qf.domain.Goods;
import com.qf.domain.GoodsType;
import com.qf.utils.DataSourceUtils;
import com.qf.utils.TxUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author YDW
 * projectName:shopping
 * time:2022/4/19 19:35
 * description:
 */
public class GoodsDaoImpl implements GoodsDao {
    QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public Long findTotalCount(int typeId) {
        String sql=" select count(0) from tb_goods where  typeid=? ";
        try {
            Long totalCount = (Long) queryRunner.query(sql, new ScalarHandler(),typeId);
            return totalCount;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Long.valueOf(0);

    }

    @Override
    public List<Goods> findData(int typeId, int startindex, int pageSize) {
        String sql=" select id,name,pubdate,picture,price,star,intro,typeid from tb_goods where typeid=? limit ?,? ";
        try {
            List<Goods> data=queryRunner.query(sql, new BeanListHandler<>(Goods.class),typeId,startindex,pageSize);
            return data;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Goods findGoodsById(int id) {
        String sql=" select id,name,pubdate,picture,price,star,intro,typeid from tb_goods where id=? ";
        try {
            Goods goods=queryRunner.query(sql, new BeanHandler<>(Goods.class),id);
            return goods;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Goods> selectAll() {
        String sql=" select id,name,pubdate,picture,price,star,intro,typeid from tb_goods";
        try {
            List<Goods> goodsList=queryRunner.query(sql, new BeanListHandler<>(Goods.class));
            return goodsList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void insertGoods(Goods goods) {
        QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
        String sql=" insert into tb_goods (id,name,pubdate,picture,price,star,intro,typeid) values(null,?,?,?,?,?,?,?)";
        try {
            queryRunner.update(sql,goods.getName(),goods.getPubdate(),goods.getPicture(),goods.getPrice(),goods.getStar(),goods.getIntro(),goods.getTypeid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
